package com.estock.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
	
	public static final String CHARSET_UTF8 = "UTF-8";
	private static final String DEFAULT_CONTENT_CHARSET = CHARSET_UTF8;
	
	public static String readString(String fileName, final String defaultCharset) {
		String charset = defaultCharset;
        if (charset == null) {
            charset = DEFAULT_CONTENT_CHARSET;
        }
        
	    BufferedReader reader = null;
		try {
			reader = new BufferedReader(
					new InputStreamReader(new FileInputStream(fileName), charset));
			StringBuilder sb = new StringBuilder();
	        int l;
	        try {
	            char[] tmp = new char[2048];
	            while ((l = reader.read(tmp)) != -1) {
	                sb.append(tmp, 0, l);
	            }
	        } finally {
	        	reader.close();
	        }
	        return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException("Error happened while reading from file: " + fileName);
		}  
	}
	
	public static void writeString(String fileName, String content) {
	    BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(fileName));
			writer.write(content); 
		} catch (Exception e) {
			throw new RuntimeException("Error happened while writing to file: " + fileName);
		} finally {
	        try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	}
	
	public static void writeBytes(String fileName, byte[] bytes, boolean append) {
		File file = new File(fileName);
		createIfNotExists(file);
		
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file, append);
			fos.write(bytes);
		    fos.flush();
		} catch (FileNotFoundException e) {
			logger.warn("No file found when try writing file: " + file.getAbsolutePath());
		} catch (IOException e) {
			logger.warn("IO exception happened when try writing file: " + file.getAbsolutePath());
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				logger.warn("Error in closing connection in writing filename: " + file.getAbsolutePath());
			}
		}
	}

	public static void createIfNotExists(File file) {
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			try {
				file.createNewFile();
			} catch (IOException e) {
				logger.info("Error in creating file: " + file.getAbsolutePath());
				return;
			}
		}
	}
	
}
